from rest_framework import serializers
from home import models
from django.conf import settings
from rest_framework.serializers import ValidationError


class ProjectAllCommentViewSerializer(serializers.ModelSerializer):
    """
    ymq
    产品详细评论序列化
    """
    comment_list = serializers.SerializerMethodField()
    comment_list2 = serializers.SerializerMethodField()

    class Meta:
        model = models.Project
        fields = ['comment_list', 'comment_list2']

    def get_comment_list(self, obj):
        """
        根评论
        """
        """
        
        comment_list: [
          {
            comment_id: 1, //评论id
            comment_pr_id: 1, //评论文章所属id
            comment_user_avatar: 'https://cclove.club/xcx/user.jpg', //评论用户头像(路径替换为你的图片路径)
            comment_user_name: '高飞', //评论人昵称
            comment_text: '去办理优待证是挺难的，但是办理了优待证之后福利特别好', //评论内容
            comment_time: '2020年8月18日', //评论时间
            reply_id: 0, //回复谁的评论，默认为0
            parent_id: 0, //评论所属评论id，默认为0
            reply_name: '' //回复评论用户的昵称 默认为''
          }
    ],
        """
        # 获取当前产品的 所有根评论
        # print(obj, 'obj')
        project_comment_list = obj.pc_p.filter(is_delete=False, is_show=True, reply__isnull=True).all()
        # print(project_comment_list, '>>>>')
        comment_list = [
            {'comment_id': item.id, 'comment_pr_id': item.project.id, 'comment_user_avatar': item.userinfo.icon,
             'comment_user_name': item.userinfo.username, 'comment_text': item.comment,
             'comment_time': str(item.create_time.strftime('%Y-%m-%d %H:%M:%S')).replace('T', ' '), 'reply_id': 0,
             'parent_id': 0, 'reply_name': ''}
            for item in project_comment_list]

        return comment_list

    def get_comment_list2(self, obj):
        """
        子评论
        """
        """
         comment_list2: [
          {
            comment_id: 4, //评论id
            comment_pr_id: 1, //评论文章所属id
            comment_user_name: '张剑锋', //评论人昵称
            comment_user_avatar: 'https://cclove.club/xcx/user.jpg', //评论用户头像
            comment_text: "大家快去办理吧!!!",//评论内容
            comment_time: '2020年8月18日',  //评论时间
            reply_id: 3,  //回复谁的评论，
            parent_id: 3, //评论所属评论id，
            reply_name: '' //回复评论用户的昵称  默认为''
          },
          {
            comment_id: 5,
            comment_pr_id: 1,
            comment_user_name: '沈非隆',
            comment_user_avatar: 'https://cclove.club/xcx/user.jpg',
            comment_text: "办理优待证大概需要多长时间呢会不会需要特别长时间",
            comment_time: '2020年8月18日',
            reply_id: 3,
            parent_id: 3,
            reply_name: '张剑锋'
          }
    ],
        
        """
        project_comment_list = obj.pc_p.filter(is_delete=False, is_show=True, reply__isnull=False).all()

        comment_list2 = [
            {'comment_id': item.id, 'comment_pr_id': item.project.id, 'comment_user_avatar': item.userinfo.icon,
             'comment_user_name': item.userinfo.username, 'comment_text': item.comment,
             'comment_time': str(item.create_time.strftime('%Y-%m-%d %H:%M:%S')).replace('T', ' '),
             'reply_id': item.userinfo_id,
             'parent_id': item.reply_id, 'reply_name': item.reply.userinfo.username}
            for
            item in project_comment_list]
        # print(project_comment_list, '<<<<<')

        return comment_list2


class ProjectCommentCreateSerializer(serializers.ModelSerializer):
    """
    创建商品评论
    """
    comment_user_name = serializers.CharField(write_only=True)
    comment_user_avatar = serializers.CharField(write_only=True)
    comment_text = serializers.CharField(write_only=True)
    reply_id = serializers.CharField(write_only=True)
    parent_id = serializers.CharField(write_only=True)
    comment_pr_id = serializers.CharField(write_only=True)
    reply_name = serializers.CharField(write_only=True, allow_null=True, allow_blank=True)

    class Meta:
        model = models.Project
        fields = ['comment_user_name', 'comment_user_avatar', 'comment_text', 'reply_id', 'parent_id', 'reply_name',
                  'comment_pr_id']

    def create(self, validated_data):
        """
        创建
        """
        """
        {
            'new_comment_data': 
            {
            'comment_id': 1, 
            'comment_user_name': '马飞', 
            'comment_user_avatar': 'https://cclove.club/xcx/user.jpg',
             'comment_text': 'zhen', 
             'comment_time': '2023年7月20日19时24分3秒',
              'reply_id': 0, ' // 回复用户id
              parent_id': 0,  // 回复上一级id
              'reply_name': None
              }
          }
                 
        
        
        """
        # 3 处修改  获取token

        # comment_request_dic = self.context['request'].data
        # 登录用户
        user = self.context['request'].user

        # print(user, '>>>>>')
        # print(validated_data, '>>>>>')
        # 判断
        if not user:
            raise ValidationError('不合法发言')

        reply_id = validated_data.get('parent_id', None)
        # # 进行深度增加
        if int(reply_id) != 0:
            # 当前评论的id
            reply_obj = models.ProjectComment.objects.get(id=reply_id)
            reply_obj.depth += 1
            new_depth = reply_obj.depth
        else:
            new_depth = 1
        project_id = validated_data.get('comment_pr_id')
        # 数据创建
        comment_obj = models.ProjectComment.objects.create(project_id=project_id,
                                                           comment=validated_data.get('comment_text'),
                                                           userinfo_id=user.id,
                                                           reply_id=None if int(validated_data.get(
                                                               'parent_id')) == 0 else validated_data.get('parent_id'),
                                                           depth=new_depth
                                                           )
        # 评论数加一
        obj = models.Project.objects.get(pk=project_id)
        obj.comment_num += 1
        obj.save()
        return comment_obj
